import { defineStore } from 'pinia';
import {
  getUserInfo,
} from '@/api/user';
import {
  type LoginData,
  login as userLogin,
  logout as userLogout,
} from '@/api/auth';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
// eslint-disable-next-line import/no-cycle
import { useMenuStore } from '@/store';
import { UserState } from './types';

// @ts-ignore
const useUserStore = defineStore('user', {
  state: (): UserState => ({
    id: undefined,
    username: undefined,
    realname: undefined,
    nickname: undefined,
    avatar: undefined,
    email: undefined,
    mobile: undefined,
    intro: undefined,
    gender: undefined,
    roles: [],
    permission: [],
  }),
  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },
  actions: {
    // 设置用户信息
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // 重置用户信息
    resetInfo() {
      this.$reset();
    },
    //  获取用户信息
    async info() {
      const res = await getUserInfo();
      // 设置用户信息
      this.setInfo(res.data);
    },

    // 登录
    async login(loginForm: LoginData) {
      try {
        const res = await userLogin(loginForm);
        setToken(res.data.access_token);
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    // 登出回调
    logoutCallBack() {
      this.resetInfo();
      clearToken();
      // 移除路由监听器
      removeRouteListener();
      // 清空菜单
      const menuStore = useMenuStore();
      menuStore.clearMenu();
    },
    // 登出
    async logout() {
      try {
        await userLogout();
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useUserStore;
